package com.xzx.spark.tuning.explain

import com.xzx.spark.tuning.utils.InitUtil
import org.apache.spark.SparkConf
import org.apache.spark.sql.execution.{CodegenMode, ExtendedMode, FormattedMode, SimpleMode}

/**
 *
 * ${DESCRIPTION}
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2022-03-04 7:39 PM
 */
object ExplainDemo {
  def main(args: Array[String]): Unit = {
    val sparkConf = new SparkConf().setAppName(ExplainDemo.getClass.getSimpleName)
      .setMaster("local[*]")
    val sparkSession = InitUtil.initSparkSession(sparkConf)

    sparkSession.sql("use sparktuning;")
    val sqlstr =
      """
        |select
        |  sc.courseid,
        |  sc.coursename,
        |  sum(sellmoney) as totalsell
        |from sale_course sc join course_shopping_cart csc
        |  on sc.courseid=csc.courseid and sc.dt=csc.dt and sc.dn=csc.dn
        |group by sc.courseid,sc.coursename
      """.stripMargin

    println("=====================================explain()-只展示物理执行计划============================================")
    sparkSession.sql(sqlstr).explain()

    println("===============================explain(mode = \"simple\")-只展示物理执行计划=================================")
    sparkSession.sql(sqlstr).explain(SimpleMode.name)

    println("============================explain(mode = \"extended\")-展示逻辑和物理执行计划==============================")
    sparkSession.sql(sqlstr).explain(ExtendedMode.name)

    println("============================explain(mode = \"codegen\")-展示可执行java代码===================================")
    sparkSession.sql(sqlstr).explain(CodegenMode.name)

    println("============================explain(mode = \"formatted\")-展示格式化的物理执行计划=============================")
    sparkSession.sql(sqlstr).explain(FormattedMode.name)

  }

}
